#!/bin/bash
# Go cross-compile
# Usually, only the VERSION changes.
# The OSLIST and ARCHLIST can change, as well.
# No need to change anything below ####
#

TOOLNAME=mcp-imagen-go

# Extract version from main.go
# Looks for a line like: const version = "1.2.0"
# - grep -m 1 'const version = ': Finds the first line containing 'const version = '.
# - awk -F'"' '{print $2}': Splits the line by double quotes and prints the second field.
VERSION=$(grep -m 1 'const version = ' imagen.go | awk -F'"' '{print $2}')

# Check if VERSION was successfully extracted
if [ -z "$VERSION" ]; then
    echo "Error: Could not extract version from imagen.go"
    echo "Please ensure imagen.go contains a line like: const version = \"x.y.z\""
    exit 1
fi

echo "Extracted Version: $VERSION"

OSLIST=(linux darwin windows)
ARCHLIST=(amd64 386)

####

DISTDIR=dist/${VERSION}
mkdir -p ${DISTDIR}

echo "Compiling version ${VERSION}:"
for os in ${OSLIST[*]}; do
  for arch in ${ARCHLIST[*]}; do
  	EXT=""
  	if [[ ${os} == "windows" ]]; then
  		EXT=".exe"
  	fi
  	GOOS=${os}
  	GOARCH=${arch}
  	echo "Compiling ${GOOS}/${GOARCH}..."
  	OUTPUTFILE=${DISTDIR}/${TOOLNAME}-${VERSION}-${GOOS}.${GOARCH}${EXT}
    GOOS=${GOOS} GOARCH=${GOARCH} go build -trimpath -o ${OUTPUTFILE} *.go
    file ${OUTPUTFILE}
  done
done
# for distributions - homebrew & scoop
cd ${DISTDIR}
# for homebrew distribution, rename darwin.amd64, gz, shasum
cp ${TOOLNAME}-${VERSION}-darwin.amd64 ${TOOLNAME}
tar -czf ${TOOLNAME}-${VERSION}.tar.gz ${TOOLNAME}
shasum -a 256 ${TOOLNAME}-${VERSION}.tar.gz > ${TOOLNAME}-${VERSION}.tar.gz.shasum256
# for scoop distribution, rename windows.amd64.exe, zip, shasum
cp ${TOOLNAME}-${VERSION}-windows.amd64.exe ${TOOLNAME}.exe
zip ${TOOLNAME}-${VERSION}.64.exe.zip ${TOOLNAME}.exe
shasum -a 256 ${TOOLNAME}-${VERSION}.64.exe.zip > ${TOOLNAME}-${VERSION}.64.exe.zip.shasum256
